package com.lc.common.component;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lc.common.bean.response.LoginInfo;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;


/**
 * 过滤器
 * <p>
 * 获取当前登陆者 并且放入 ThreadLocal 中
 *
 * @author ch
 */
@Configuration
@SuppressWarnings("unused")
public class ComponentFilter extends AbstractStorage implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
        clear();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String header = httpRequest.getHeader("login-info");
        if (!StrUtil.isBlank(header)) {
            String result = URLDecoder.decode(header, String.valueOf(StandardCharsets.UTF_8));
            LoginInfo loginInfo = JSONUtil.toBean(result, LoginInfo.class);
            setValue(loginInfo);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        clear();
    }
}
